<?php

namespace app\payment\admin;

use app\common\builder\ZBuilder;
use app\payment\model\Order as OrderModel;
use app\payment\model\PaymentPayCompany as PaymentPayCompanyModel;
use app\payment\model\SimulationNotify as SimulationNotifyModel;
use app\payment\model\Mconfig as MconfigModel;
use app\payment\model\Download as DownloadModel;
use app\api\model\PaymentOrder as ApiPaymentOrderModel;
use think\facade\Env;
use think\facade\Request;
use think\Db;

/**
 * 订单控制器
 * @package app\payment\admin
 */
class Order extends Index
{

    protected function initialize()
    {
        parent::initialize();

        if (in_array(request()->action(), ['simulation_notify', 'simulation_notify_add'])) {
            if (!$this->simulation_pay_notify_safe) {
                $this->error('NO');
            }
        }
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        // 获取查询条件
        $map = $this->getMap();

        if ($map) {
            foreach ($map as $map_k1 => $map_v1) {

                if ($map_v1[0] == 'cash') {
                    $map[$map_k1][2] = $map[$map_k1][2] * 100;
                }
                if ($map_v1[0] == 'create_param') {
                    $map[$map_k1][1] = 'like';
                    $map[$map_k1][2] = '%' . $map[$map_k1][2] . '%';
                }
                if ($map_v1[0] == 'notify_param') {
                    $map[$map_k1][1] = 'like';
                    $map[$map_k1][2] = '%' . $map[$map_k1][2] . '%';
                }
                if ($map_v1[0] == 'merchant_id') {
                    $search_merchant_id_key = $map_k1;
                    $search_merchant_id = $map[$map_k1][2];
                }
            }
        }

        $search_merchant_id_key = isset($search_merchant_id_key) ? $search_merchant_id_key : count($map);

        if ($this->no_auth) {
            $map[$search_merchant_id_key] = ['merchant_id', '=', $this->merchant_id];
        }

        if ($this->is_agent) {
            $sub_merchant = get_sub_merchant($this->merchant_id);
            if ($sub_merchant) {
                $sub_merchant[] = $this->merchant_id;
                $map[$search_merchant_id_key] = ['merchant_id', 'in', $sub_merchant];
                if (isset($search_merchant_id) && in_array($search_merchant_id, $sub_merchant)) {
                    $map[$search_merchant_id_key] = ['merchant_id', '=', $search_merchant_id];
                }
            }
        }

        $list_rows = input('list_rows', 10) >= 10 ? 10 : input('list_rows');
        // 数据列表
        $data_list = OrderModel::where($map)->field(true)->order('create_time desc')->paginate($list_rows);

        $sum_count = $data_list->toArray()['total'];

        $sum_cash = OrderModel::where($map)->sum('cash');
        $sum_cash /= 100;
        // 分页数据
        $page = $data_list->render();

        // 所有的支付类型
        $all_payment_type = pay_config('payment_type');
        // 所有的订单状态
        $all_order_status = pay_config('order_status');
        // 所有的支付公司
        $all_config_group = pay_config('config_group');
        unset($all_config_group['pay_config']);
        // 所有的支付公司子商户号
        $all_child_company = PaymentPayCompanyModel::order(['group' => 'asc', 'sort' => 'asc', 'title' => 'asc', 'name' => 'asc'])->column('title', 'name');

        $date = date('Y-m-d');
        $appidName = '';
        $class = true;
        if ($this->no_auth) {
            $appidName = $this->merchant_id;
            $class = false;
        }
        $all_appid = OrderModel::appidName($appidName, $class);
        $search = [
            ['daterange:6', 'create_time', '时间查询', '', "$date 00:00:00 - $date 23:59:59", ['max-date' => "$date 23:59:59", 'format' => 'YYYY-MM-DD HH:mm:ss', 'time-picker' => 'true', 'time-picker24-hour' => 'true', 'time-picker-seconds' => 'true']],
            ['select:3', 'status', '支付状态', '', '', $all_order_status],
            ['select:3', 'type', '支付类型', '', '', $all_payment_type],
            ['text:3', 'merchant_order_id', '商户订单号'],
            ['text:3', 'cash', '订单金额'],
            ['select:3', 'app_id', '所属应用', '', '', $all_appid],
            ['text:3', 'user_id', '用户ID'],
            ['text:3', 'order_id', '平台订单号'],
            ['text:3', 'create_param', '商户参数'],
            ['select:3', 'company', '总支付公司', '', '', $all_config_group],
            ['select:3', 'child_company', '子公司名称', '', '', $all_child_company],
            ['text:3', 'other_order_id', '第三方订单号'],
            ['text:3', 'notify_param', '第三方参数'],
            ['text:3', 'merchant_id', '商户号'],
        ];

        $items = [
            ['create_time', '发起时间', 'datetime', '', 'Y-m-d H:i:s'],
            ['merchant_id', '商户', 'callback', function ($value) {
                return $value . '<br/>' . get_user_nickname($value);
            }, '', 'text-center'],
            ['merchant_order_id', '商户订单号'],
            ['order_id', '平台订单号'],
            ['other_order_id', '第三方订单号'],
            ['user_ip', '用户和IP地址', 'callback', function ($value) {
                $create_param = json_decode($value['create_param'], true);
                $user_id = $value['user_id'] ? $value['user_id'] . '<br/>' : '';
                return $user_id . $create_param['ip'];
            }, '__data__', 'text-center'],
            ['app_id', '应用名称', 'callback', function ($value) {
                return $value ? OrderModel::appName($value) : '';
            }, '', 'text-center'],
            ['cash', '金额', 'callback', function ($value) {
                return $value / 100;
            }],
            ['type', '支付类型', '', '', $all_payment_type],
            ['update_time', '完成时间', 'datetime', '', 'Y-m-d H:i:s'],
            ['status', '状态', 'status', '', $all_order_status],
            ['child_company', '子公司', 'callback', function ($child_company, $all_child_company) {
                return isset($all_child_company[$child_company]) ? $all_child_company[$child_company] : $child_company;
            }, $all_child_company],
            ['right_button', '操作', 'btn']
        ];

        if ($this->no_auth) {
            // 去掉显示搜索项          
            unset($search[8]);
            unset($search[9]);
            unset($search[10]);
            unset($search[11]);
            unset($search[12]);
            unset($search[13]);
            // 去掉显示列
            unset($items[1]);
            unset($items[4]);
            unset($items[11]);
        }
        if ($this->is_agent) {
            // 显示搜索项
            $search[] = ['text:3', 'merchant_id', '商户号'];
            // 显示列
            array_unshift($items, ['merchant_id', '商户', 'callback', function ($value) {
                return $value . '<br/>' . get_user_nickname($value);
            }, '', 'text-center']);
        }

        $describe = [
            'title' => "总笔数：{$sum_count} 笔    总金额：{$sum_cash} 元",
            'icon' => 'fa fa-fw fa-jpy',
            'class' => 'btn btn-xs btn-info',
        ];
        // 分析
        $analyse = [
            'title' => '分析',
            'icon' => 'fa fa-fw fa-deviantart',
            'class' => 'btn btn-xs btn-success',
            'href' => url('analyse')
        ];
        $export = [
            'title' => '导出',
            'icon' => 'fa fa-fw fa-arrow-circle-o-down',
            'target' => '_blank',
            'class' => 'btn btn-xs btn-default',
            'href' => url('export', ['map' => json_encode($map)]),
            'data-title' => '真的要导出吗？',
            'data-tips' => '导出可能要点时间,请再次点击导出',
        ];

        $simulation_notify = <<<EOF
<a title="模拟通知列表" style="margin-bottom:6px;" class="btn btn-xs btn-success" href="simulation_notify" >
<i class="fa fa-fw fa-bolt"></i>
模拟通知列表
</a> 
EOF;

        $mconfig = MconfigModel::where(['id' => $this->merchant_id])->find();
        if (!$mconfig || $mconfig['simulation_notify'] != 1) {
            $simulation_notify = '';
        }

        // 交易密码不能等于123456
        $tips = '';
        if ($this->merchant_info['trade_pwd'] == md5(md5(md5('123456')))) {
            $url = url('mconfig/editpwd', "id={$this->merchant_id}");
            $tips = "您的默认交易密码是123456，请修改！<a title='点击修改' class='btn btn-primary' href='{$url}'> 点击修改！</a>";
        }

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->hideCheckbox()
            ->setPageTitle('订单列表') // 设置页面标题
            ->setTableName('payment_order') // 设置数据表名
            ->setPrimaryKey('order_id') // 设置主键名为id
            ->addColumns($items) // 批量添加列
            ->addRightButton('see', ['title' => '查看', 'icon' => 'fa fa-fw fa-eye', 'href' => url('see', ['id' => '__id__'])], true)
            ->addRightButton('notify', ['title' => '通知', 'class' => 'ajax-get confirm', 'data-title' => '真的要通知吗？', 'data-tips' => '商户系统要能够处理重复通知！', 'icon' => 'fa fa-fw fa-forumbee', 'href' => url('notify', ['id' => '__id__'])])
            ->setSearchArea($search) // 设置搜索区域
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->addTopButton('describe', $describe) // 添加按钮
            ->addTopButton('analyse', $analyse) // 添加按钮
            ->addTopButton('export', $export) // 添加按钮
            ->setExtraHtml($simulation_notify, 'toolbar_top')
            ->replaceRightButton(['status' => ['<>', 2]], '', 'notify') // 替换右侧按钮
            ->replaceRightButton(['create_time' => ['<', time() - 86400 * 30]], '', 'notify') // 替换右侧按钮
            ->setPageTips($tips)
            ->fetch(); // 渲染页面
    }

    /**
     * 分析
     * @return mixed
     */
    public function analyse()
    {
        $data = $this->request->get();
        // 保存数据
        if ($data) {

            $count = $data['count'] ? $data['count'] : 0;
            if ($this->no_auth) {
                $data['merchant_id'] = $this->merchant_id;
            }

            if ($data['merchant_id']) {
                $temp_map[] = ['merchant_id', '=', $data['merchant_id']];
            }
            if ($data['user_id']) {
                $temp_map[] = ['user_id', '=', $data['user_id']];
            }
            if ($data['app_id']) {
                $temp_map[] = ['app_id', '=', $data['app_id']];
            }
            if ($data['create_param']) {
                $temp_map[] = ['create_param', 'like', '%' . $data['create_param'] . '%'];
            }
            if ($data['notify_param']) {
                $temp_map[] = ['notify_param', 'like', '%' . $data['notify_param'] . '%'];
            }
            if ($data['status']) {
                $temp_map[] = ['status', '=', $data['status']];
            }
            if (isset($data['child_company']) && $data['child_company']) {
                $temp_map[] = ['child_company', '=', $data['child_company']];
            }

            $temp_map[] = ['create_time', ['>=', strtotime($data['start_time'])], ['<', strtotime($data['end_time'])]];

            $list_rows = input('list_rows', 10);
            // 数据列表
            $data_list = Db::name('payment_order')
                ->where($temp_map)
                ->field('merchant_id,user_id,app_id,count(user_id) as counts,sum(cash) as cashs')
                ->group('user_id')
                ->having("count(user_id)>={$count}")
                ->paginate($list_rows);

            // 分页数据
            $page = $data_list->render();

            $items = [
                ['__INDEX__', '#'],
                ['merchant_id', '商户', 'callback', function ($value) {
                    return $value . '<br/>' . get_user_nickname($value);
                }, '', 'text-center'],
                ['user_id', '用户ID'],
                ['app_id', '应用名称', 'callback', function ($value) {
                    return $value ? $value . '<br/>' . OrderModel::appName($value) : '';
                }, '', 'text-center'],
                ['cashs', '总金额（元）', 'callback', function ($value) {
                    return $value / 100;
                }],
                ['counts', '次数'],
            ];

            // 使用ZBuilder快速创建数据表格
            return ZBuilder::make('table')
                ->hideCheckbox()
                ->setPageTitle('分析用户') // 设置页面标题
                ->addColumns($items) // 批量添加列
                ->setRowList($data_list) // 设置表格数据
                ->setPages($page) // 设置分页数据
                ->fetch(); // 渲染页面
        }

        // 所有的订单状态
        $all_order_status = pay_config('order_status');

        // 支付公司    
        $payment_company = PaymentPayCompanyModel::where(['status' => 1])->order('sort asc,name asc')->column('title', 'name');

        $start_time = date("Y-m-d");
        $end_time = date("Y-m-d") . ' 23:59:59';

        $items = [
            ['text', 'merchant_id', '商户号', ''],
            ['text', 'user_id', '用户ID', ''],
            ['text', 'app_id', '应用ID', ''],
            ['text', 'create_param', '其它参数', ''],
            ['text', 'notify_param', '第三方参数', ''],
            ['text', 'count', '大于等于次数', '', 1],
            ['radio', 'status', '状态', '', $all_order_status, 2],
            ['select', 'child_company', '支付子公司', '', $payment_company],
            ['datetime', 'start_time', '开始日期', '', $start_time],
            ['datetime', 'end_time', '结束日期', '', $end_time],
        ];
        if ($this->no_auth) {
            unset($items[0]);
            unset($items[7]);
        }

        $tips = '分析用户！';

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('分析用户') // 设置页面标题
            ->setPageTips($tips)
            ->addFormItems($items)
            ->method('get')
            ->isAjax(false)
            ->fetch();
    }

    /**
     * 导出数据
     * @return mixed
     */
    public function export($map = '')
    {
        ini_set('memory_limit', '1024M');
        ob_end_clean();

        if (!is_dir($this->file_path)) {
            $this->error('数据导出目录不存在！', url('index'));
        }
        set_time_limit(3600);

        if (!empty($map)) {
            $map = htmlspecialchars_decode($map);
            $map = urldecode($map);
            $map = str_replace("+", " ", $map);
            // 获取查询条件
            $map = json_decode($map, true);
        }

        // 所有的支付类型
        $all_payment_type = pay_config('payment_type');
        // 所有的交易类型
        $all_trade_type = pay_config('trade_type');
        // 所有的订单状态
        $all_order_status = pay_config('order_status');
        // 所有的支付公司
        $all_config_group = pay_config('config_group');
        unset($all_config_group['pay_config']);
        // 获取所有支付公司的子商户号
        $all_child_company = PaymentPayCompanyModel::column('title', 'name');

        if ($map) {
            foreach ($map as $map_k1 => $map_v1) {

                if ($map_v1[0] == 'merchant_id') {
                    $search_merchant_id_key = $map_k1;
                    $search_merchant_id = $map[$map_k1][2];
                }
            }
        }

        $search_merchant_id_key = isset($search_merchant_id_key) ? $search_merchant_id_key : count($map);

        if ($this->no_auth) {
            $map[$search_merchant_id_key] = ['merchant_id', '=', $this->merchant_id];
        }

        if ($this->is_agent) {
            $sub_merchant = get_sub_merchant($this->merchant_id);
            if ($sub_merchant) {
                $sub_merchant[] = $this->merchant_id;
                $map[$search_merchant_id_key] = ['merchant_id', 'in', $sub_merchant];
                if (isset($search_merchant_id) && in_array($search_merchant_id, $sub_merchant)) {
                    $map[$search_merchant_id_key] = ['merchant_id', '=', $search_merchant_id];
                }
            }
        }

        $count = OrderModel::where($map)->count();
        if (empty($count)) {
            $this->error('数据导出为空！', url('index'));
        }
        // 最多导出数量
        $export_order_max_count = pay_config('export_order_max_count');
        if ($count > $export_order_max_count) {
            $this->error("系统设置一次最多导出{$export_order_max_count}条数据！");
        }

        $date = date('Y-m-d');
        // 商户每天最多导出订单次数
        $order_export_day_count = pay_config('order_export_day_count');
        $order_map[] = ['merchant_id', '=', $this->merchant_id];
        $order_map[] = ['create_time', 'between time', ["$date 00:00:00", "$date 23:59:59"]];
        $download_count = DownloadModel::where($order_map)->count();
        if ($download_count >= $order_export_day_count) {
            $this->error("系统设置商户每天最多导出订单次数是{$order_export_day_count}次！");
        }

        $download['id'] = date('YmdHis') . rand(100000, 999999);
        $download['merchant_id'] = $this->merchant_id;
        $download['title'] = "支付订单导出条数（{$count}）";
        $download['file_name'] = $download['id'] . '.csv';
        $download['url'] = Request::module() . '/' . Request::controller() . '/' . Request::action();
        $download['status'] = 2;
        $download['programmer_remark'] = json_encode($map);
        $download_insert = DownloadModel::create($download);
        if (!$download_insert) {
            $this->error("导出失败！");
        }

        $field = [
            'order_id',
            'merchant_id',
            'app_id',
            'cash',
            'status',
            'type',
            'trade_type',
            'create_time',
            'update_time',
            'merchant_order_id',
            'company',
            'child_company',
            'other_order_id',
        ];
        if ($this->no_auth) {
            unset($field[10]);
            unset($field[11]);
            unset($field[12]);
        }

        $cellName = [
            '平台订单号',
            '商户号',
            '应用ID',
            '金额',
            '订单状态',
            '支付类型',
            '交易类型',
            '创建时间',
            '更新时间',
            '商户订单号',
            '支付公司',
            '支付公司子商户号',
            '第三方订单号',
        ];
        if ($this->no_auth) {
            unset($cellName[10]);
            unset($cellName[11]);
            unset($cellName[12]);
        }
        $fp = fopen($download['file_name'], 'w');

        foreach ($cellName as $key => $value) {
            $cellName[$key] = mb_convert_encoding($cellName[$key], 'gb2312', 'utf-8');
        }

        fputcsv($fp, $cellName);

        Db::name('payment_order')
            ->where($map)
            ->field($field)
            ->chunk(200, function ($all) use ($fp, $all_order_status, $all_payment_type, $all_trade_type, $all_config_group, $all_child_company) {
                foreach ($all as $single) {

                    $single['cash'] /= 100;
                    $single['status'] = $all_order_status[$single['status']];

                    $single['type'] = $all_payment_type[$single['type']];

                    $single['trade_type'] = $all_trade_type[$single['trade_type']];

                    $single['create_time'] = date('Y-m-d H:i:s', $single['create_time']);
                    $single['update_time'] = $single['update_time'] ? date('Y-m-d H:i:s', $single['update_time']) : 0;

                    if (isset($single['company'])) {
                        $single['company'] = isset($all_config_group[$single['company']]) ? $all_config_group[$single['company']] : $single['company'];
                    }
                    if (isset($single['child_company'])) {
                        $single['child_company'] = isset($all_child_company[$single['child_company']]) ? $all_child_company[$single['child_company']] : $single['child_company'];
                    }

                    foreach ($single as $key => $value) {
                        if (!in_array($key, ['cash', 'merchant_id'])) {
                            $single[$key] = "\t" . mb_convert_encoding($value, 'gb2312', 'utf-8');
                        }
                    }

                    fputcsv($fp, $single);
                    unset($single);
                }
            }, 'order_id', 'desc');
        fclose($fp);

        DownloadModel::update(['id' => $download['id'], 'status' => 1, 'update_time' => time()]);
        rename(Env::get('root_path') . 'public' . DIRECTORY_SEPARATOR . $download['file_name'], $this->file_path . $download['file_name']); // 移动到新目录

        $this->success('导出成功', url('download/index'));
    }

    /**
     * 导出数据Excel
     * @return mixed
     */
    public function export01($map = '')
    {
        if (!empty($map)) {
            $map = htmlspecialchars_decode($map);
            $map = urldecode($map);
            $map = str_replace("+", " ", $map);
            // 获取查询条件
            $map = json_decode($map, true);
        }

        // 所有的支付类型
        $all_payment_type = pay_config('payment_type');
        // 所有的交易类型
        $all_trade_type = pay_config('trade_type');
        // 所有的订单状态
        $all_order_status = pay_config('order_status');
        // 所有的支付公司
        $all_config_group = pay_config('config_group');
        unset($all_config_group['pay_config']);
        // 获取所有支付公司的子商户号
        $all_child_company = PaymentPayCompanyModel::column('title', 'name');
        if ($this->no_auth) {
            $map[] = ['merchant_id', '=', $this->merchant_id];
        }

        $count = OrderModel::where($map)->count();
        if (empty($count)) {
            $this->error('数据导出为空');
        }
        // 最多导出数量
        $export_order_max_count = pay_config('export_order_max_count');
        if ($count > $export_order_max_count) {
            $this->error("系统设置一次最多导出{$export_order_max_count}条数据！");
        }

        $field = [
            'order_id',
            'merchant_id',
            'app_id',
            'cash',
            'status',
            'type',
            'trade_type',
            'create_time',
            'update_time',
            'merchant_order_id',
            'company',
            'child_company',
            'other_order_id',
        ];
        if ($this->no_auth) {
            unset($field[10]);
            unset($field[11]);
            unset($field[12]);
        }
        // 数据列表
        $data_list = OrderModel::where($map)->order('order_id desc')->field($field)->select();

        foreach ($data_list as &$value) {
            $value['cash'] /= 100;
            $value['status'] = $all_order_status[$value['status']];
            $value['type'] = $all_payment_type[$value['type']];
            $value['trade_type'] = $all_trade_type[$value['trade_type']];
            if (isset($value['company'])) {
                $value['company'] = $all_config_group[$value['company']];
            }
            if (isset($value['child_company'])) {
                $value['child_company'] = $all_child_company[$value['child_company']];
            }
            $value['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
            $value['update_time'] = $value['update_time'] ? date('Y-m-d H:i:s', $value['update_time']) : 0;
        }
        $cellName = [
            ['order_id', 'auto', '平台订单号'],
            ['merchant_id', 'auto', '商户号'],
            ['app_id', 'auto', '应用ID'],
            ['cash', 'auto', '金额'],
            ['status', 'auto', '订单状态'],
            ['type', 'auto', '支付类型'],
            ['trade_type', 'auto', '交易类型'],
            ['create_time', 'auto', '创建时间'],
            ['update_time', 'auto', '更新时间'],
            ['merchant_order_id', 'auto', '商户订单号'],
            ['company', 'auto', '支付公司'],
            ['child_company', 'auto', '支付公司商户号'],
            ['other_order_id', 'auto', '第三方订单号'],
        ];
        if ($this->no_auth) {
            unset($cellName[10]);
            unset($cellName[11]);
            unset($cellName[12]);
        }
        // 调用插件（传入插件名，[导出文件名、表头信息、具体数据]）
        plugin_action('Excel/Excel/export', ['test', $cellName, $data_list]);
    }

    /**
     * 查看
     * @param null $id 
     * @return mixed
     */
    public function see($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数！');
        }

        // 所有的支付类型
        $all_payment_type = pay_config('payment_type');
        // 所有的交易类型
        $all_trade_type = pay_config('trade_type');
        // 所有的订单状态
        $all_order_status = pay_config('order_status');
        // 支付公司
        $all_config_group = pay_config('config_group');
        // 支付公司子商户号
        $all_child_company = PaymentPayCompanyModel::column('title', 'name');

        // 获取数据
        $info = OrderModel::where('order_id', $id)->field(true)->find();
        if (!$info) {
            $this->error('不存在！');
        }

        if ($this->is_agent) {
            $sub_merchant = get_sub_merchant($this->merchant_id);
            if (in_array($info['merchant_id'], $sub_merchant)) {
                $see_auth = true;
            }
        }

        if ($this->no_auth) {
            if (!isset($see_auth) && $this->merchant_id != $info['merchant_id']) {
                $this->error('参数错误！');
            }
        }

        if (!$this->key_see_safe) {
            $create_param = json_decode($info['create_param'], true);
            if (isset($create_param['key'])) {
                unset($create_param['key']);
            }
            $info['create_param'] = json_encode($create_param);
            $info['verify_param'] = '';
        }

        $info['cash'] /= 100;
        $info['now_cash'] = $info['now_cash'] ? $info['now_cash'] / 100 : '';
        $info['status'] = $all_order_status[$info['status']];
        $info['trade_type'] = $all_trade_type[$info['trade_type']];
        $info['type'] = $all_payment_type[$info['type']];
        $info['company'] = isset($all_config_group[$info['company']]) ? $all_config_group[$info['company']] : '';
        $info['child_company'] = isset($all_child_company[$info['child_company']]) ? $all_child_company[$info['child_company']] : '';
        $info['create_param'] = format_nice($info['create_param']);
        $info['return_param'] = format_nice($info['return_param']);
        $info['notify_param'] = format_nice($info['notify_param']);

        $items = [
            ['static', 'merchant_id', '商户号', '商户名称：' . get_user_nickname($info['merchant_id']), '', '', ''],
            ['static', 'app_id', '应用id', '', '', '', ''],
            ['static', 'cash', '充值现金（元）', ''],
            ['static', 'now_cash', '实际金额（元）', '', '', '', ''],
            ['static', 'status', '订单状态', '', '', '', ''],
            ['static', 'type', '支付类型', '', '', '', ''],
            ['static', 'trade_type', '交易类型', ''],
            ['datetime', 'create_time', '订单创建时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
            ['datetime', 'update_time', '订单更新时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
            ['static', 'order_id', '平台订单号'],
            ['static', 'merchant_order_id', '商户订单号', '', '', '', ''],
            ['textarea', 'create_param', '创建数据[:无]', '', '', '', ''],
            ['textarea', 'return_param', '返回数据[:无]', '', '', '', ''],
            ['textarea', 'notify_param', '通知数据[:无]', '', '', '', ''],
            ['static', 'other_order_id', '第三方订单号', '', '', '', ''],
            ['static', 'verify_param', '验证参数', ''],
            ['static', 'company', '支付公司', '', '', '', ''],
            ['static', 'child_company', '支付公司子商户号'],
            ['static', 'remark', '备注'],
        ];
        if ($this->no_auth) {
            unset($items[12]);
            unset($items[13]);
            unset($items[14]);
            unset($items[15]);
            unset($items[16]);
            unset($items[17]);
            unset($items[18]);
        }
        if ($this->role > $this->have_auth) {
            unset($items[11]);
        }

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('查看') // 设置页面标题
            ->addFormItems($items)
            ->hideBtn('submit')
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    /**
     * 手动通知商户，订单完成
     * @param null $id 平台订单号
     * @return mixed
     */
    public function notify($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数！');
        }
        // 获取数据
        $info = OrderModel::where('order_id', $id)->field(true)->find();
        if (!$info || $info['status'] != 2) {
            $this->error('参数有误');
        }
        if (time() > $info['create_time'] + 86400 * 30) {
            $this->error('订单时间已经超过30天时间！');
        }

        if ($this->is_agent) {
            $sub_merchant = get_sub_merchant($this->merchant_id);
            if (in_array($info['merchant_id'], $sub_merchant)) {
                $see_auth = true;
            }
        }

        if ($this->no_auth) {
            if (!isset($see_auth) && $this->merchant_id != $info['merchant_id']) {
                $this->error('通知有误！');
            }
        }

        // 把支付成功信息通知给商户
        $merchant_create_param = json_decode($info['create_param'], true);
        $notify_url = $merchant_create_param['notify_url'];
        $notify_data['code'] = 10000;                                         // 成功状态码
        $notify_data['merchant_id'] = $info['merchant_id'];                   // 商户号
        $notify_data['merchant_order_id'] = $info['merchant_order_id'];       // 商户订单号
        $notify_data['order_id'] = $info['order_id'];                         // 平台订单号
        $notify_data['app_id'] = $merchant_create_param['app_id'];            // 应用id
        $notify_data['cash'] = $merchant_create_param['cash'];                // 充值现金
        $notify_data['type'] = $merchant_create_param['type'];                // 支付类型，支付宝或微信等等
        $notify_data['trade_type'] = $merchant_create_param['trade_type'];    // 交易类型：比如充值、代付
        $notify_data['time'] = $info['update_time'];                          // 更新时间
        $notify_data['extra'] = $merchant_create_param['extra'];              // 商户自定义备注
        // 订单状态：1:待支付 2:成功 3:失败 4:退款中 5:退款成功 6:退款失败 7:冻结 8:异常 9:驳回 10:关闭
        $notify_data['status'] = 2;
        $notify_data['sign'] = md5('merchant_id=' . $notify_data['merchant_id'] . '&merchant_order_id=' . $notify_data['merchant_order_id'] . '&order_id=' . $notify_data['order_id'] . '&cash=' . $notify_data['cash'] . '&type=' . $notify_data['type'] . '&time=' . $notify_data['time'] . '&key=' . $merchant_create_param['key']);
        $resdata = go_curl($notify_url, $notify_data, 'get', 12);
        if (stripos($resdata, 'success') !== false) {
            // 通知成功     
            $this->error('通知成功');
        }

        $this->error("通知失败,返回内容是：{$resdata}");
    }

    /**
     * 模拟通知订单首页
     * @return mixed
     */
    public function simulation_notify()
    {
        if ($this->no_auth) {
            $mconfig = MconfigModel::where(['id' => $this->merchant_id])->find();
            if (!$mconfig || $mconfig['simulation_notify'] != 1) {
                $this->error('权限不足！');
            }
        }

        // 获取查询条件
        $map = $this->getMap();

        if ($map) {
            foreach ($map as $map_k1 => $map_v1) {

                if ($map_v1[0] == 'cash') {
                    $map[$map_k1][2] = $map[$map_k1][2] * 100;
                }
                if ($map_v1[0] == 'create_param') {
                    $map[$map_k1][1] = 'like';
                    $map[$map_k1][2] = '%' . $map[$map_k1][2] . '%';
                }
                if ($map_v1[0] == 'merchant_id') {
                    $search_merchant_id_key = $map_k1;
                    $search_merchant_id = $map[$map_k1][2];
                }
            }
        }

        $search_merchant_id_key = isset($search_merchant_id_key) ? $search_merchant_id_key : count($map);

        if ($this->no_auth) {
            $map[$search_merchant_id_key] = ['merchant_id', '=', $this->merchant_id];
        }

        if ($this->is_agent) {
            $sub_merchant = get_sub_merchant($this->merchant_id);
            if ($sub_merchant) {
                $sub_merchant[] = $this->merchant_id;
                $map[$search_merchant_id_key] = ['merchant_id', 'in', $sub_merchant];
                if (isset($search_merchant_id) && in_array($search_merchant_id, $sub_merchant)) {
                    $map[$search_merchant_id_key] = ['merchant_id', '=', $search_merchant_id];
                }
            }
        }

        $list_rows = input('list_rows', 10) >= 10 ? 10 : input('list_rows');
        // 数据列表
        $data_list = SimulationNotifyModel::where($map)->order('update_time desc')->paginate($list_rows);

        $sum_count = SimulationNotifyModel::where($map)->count();
        $sum_cash = SimulationNotifyModel::where($map)->sum('cash');
        $sum_cash /= 100;
        // 分页数据
        $page = $data_list->render();

        // 所有的支付类型
        $all_payment_type = pay_config('payment_type');
        // 所有的交易类型
        $all_trade_type = pay_config('trade_type');
        // 所有的订单状态
        $all_order_status = pay_config('order_status');
        // 所有的支付公司
        $all_config_group = pay_config('config_group');
        unset($all_config_group['pay_config']);
        // 所有的支付公司子商户号
        $all_child_company = PaymentPayCompanyModel::order(['group' => 'asc', 'sort' => 'asc', 'title' => 'asc',  'name' => 'asc'])->column('title', 'name');

        $date = date('Y-m-d');
        $appidName = '';
        if ($this->no_auth) {
            $appidName = $this->merchant_id;
        }
        $search = [
            ['daterange:6', 'create_time', '发起时间', '', "$date 00:00:00 - $date 23:59:59", ['max-date' => "$date 23:59:59", 'format' => 'YYYY-MM-DD HH:mm:ss', 'time-picker' => 'true', 'time-picker24-hour' => 'true', 'time-picker-seconds' => 'true']],
            ['select:3', 'type', '支付类型', '', '', $all_payment_type],
            ['select:3', 'status', '支付状态', '', '', $all_order_status],
            ['text:3', 'merchant_order_id', '商户订单号'],
            ['text:3', 'cash', '订单金额'],
            ['select:3', 'trade_type', '交易类型', '', '', $all_trade_type],
            ['select:3', 'app_id', '所属应用', '', '', SimulationNotifyModel::appidName($appidName)],
            ['text:3', 'order_id', '平台订单号'],
            ['text:3', 'merchant_id', '商户号'],
            ['select:3', 'company', '总支付公司', '', '', $all_config_group],
            ['select:3', 'child_company', '子公司商户号', '', '', $all_child_company],
            ['text:3', 'other_order_id', '第三方订单号'],
            ['text:3', 'operation_id', '操作号'],
        ];

        $items = [
            ['create_time', '发起时间', 'datetime', '', 'Y-m-d H:i:s'],
            ['operation_id', '操作', 'callback', function ($value) {
                return $value . '<br/>' . get_user_nickname($value);
            }, '', 'text-center'],
            ['merchant_id', '商户', 'callback', function ($value) {
                return $value . '<br/>' . get_user_nickname($value);
            }, '', 'text-center'],
            ['merchant_order_id', '商户订单号'],
            ['order_id', '平台订单号'],
            ['other_order_id', '第三方订单号'],
            ['body', '商品名称', 'callback', function ($value) {
                $create_param = json_decode($value['create_param'], true);
                return $create_param['body'];
            }, '__data__'],
            ['app_id', '应用名称', 'callback', function ($app_id) {
                return SimulationNotifyModel::appName($app_id);
            }],
            ['cash', '金额', 'callback', function ($cash) {
                return $cash / 100;
            }],
            ['type', '支付类型', '', '', $all_payment_type],
            ['update_time', '完成时间', 'datetime', '', 'Y-m-d H:i:s'],
            ['status', '状态', 'status', '', $all_order_status],
            ['child_company', '子公司', 'callback', function ($child_company, $all_child_company) {
                return isset($all_child_company[$child_company]) ? $all_child_company[$child_company] : $child_company;
            }, $all_child_company],
            ['right_button', '操作', 'btn']
        ];

        if ($this->no_auth) {
            // 去掉显示搜索项
            unset($search[8]);
            unset($search[9]);
            unset($search[10]);
            unset($search[11]);
            unset($search[12]);
            // 去掉显示列
            unset($items[5]);
            unset($items[12]);
        }
        $describe = [
            'title' => "总笔数：{$sum_count} 笔    总金额：{$sum_cash} 元",
            'icon' => 'fa fa-fw fa-jpy',
            'class' => 'btn btn-xs btn-info',
        ];
        $export = [
            'title' => '导出',
            'icon' => 'fa fa-fw fa-arrow-circle-o-down',
            'target' => '_blank',
            'class' => 'btn btn-xs btn-default',
            'href' => url('simulation_notify_export', ['map' => urlencode(json_encode($map))]),
            'data-title' => '真的要导出吗？',
            'data-tips' => '导出可能要点时间,请再次点击导出',
        ];

        $simulation_notify_add = <<<EOF
<a title="新增模拟第三方通知" style="margin-bottom:6px;" class="btn btn-xs btn-danger" href="simulation_notify_add" >
<i class="fa fa-plus-circle"></i>
新增模拟第三方通知
</a> 
EOF;

        $mconfig = MconfigModel::where(['id' => $this->merchant_id])->find();
        if (!$mconfig || $mconfig['simulation_notify'] != 1) {
            $simulation_notify_add = '';
        }

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->hideCheckbox()
            ->setPageTitle('模拟订单通知列表') // 设置页面标题
            ->setTableName('payment_order_simulation_notify') // 设置数据表名
            ->setPrimaryKey('order_id') // 设置主键名为id
            ->addColumns($items) // 批量添加列
            ->addRightButton('simulation_notify_see', ['title' => '查看', 'icon' => 'fa fa-fw fa-eye', 'href' => url('simulation_notify_see', ['id' => '__id__'])], true)
            ->setSearchArea($search) // 设置搜索区域
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->setExtraHtml($simulation_notify_add, 'toolbar_top')
            ->addTopButton('describe', $describe) // 添加按钮
            ->addTopButton('export', $export) // 添加按钮
            ->fetch(); // 渲染页面
    }

    /**
     * 模拟第三方订单通知
     * @return mixed
     */
    public function simulation_notify_add()
    {
        $mconfig = MconfigModel::where(['id' => $this->merchant_id])->find();
        if ($this->no_auth) {
            if (!$mconfig || $mconfig['simulation_notify'] != 1) {
                $this->error('权限不足！');
            }
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();

            if ($this->merchant_info['trade_pwd'] != md5(md5(md5($data['trade_pwd'])))) {
                $this->error('交易密码不正确！');
            }

            unset($data['trade_pwd']);

            if (empty($data['order_id'])) {
                $this->error('请输入平台订单号！');
            }

            $info = OrderModel::where(['order_id' => $data['order_id']])->find();
            if (!$info) {
                $this->error('平台订单号不存在，请重新输入！');
            }
            if ($info['status'] != 1) {
                $this->error('订单号状态有误！');
            }
            if (time() > $info['create_time'] + 86400 * 30) {
                $this->error('订单时间已经超过30天时间！');
            }
            if ($this->no_auth) {
                if ($this->merchant_id != $info['merchant_id']) {
                    $this->error('参数错误,只能通知自己的平台订单号！');
                }
            }
            if ($this->role > $this->have_auth) {
                $simulation_count = SimulationNotifyModel::where(['operation_id' => $this->merchant_id])->whereTime('create_time', 'today')->count();
                $simulation_notify_count = pay_config('simulation_notify_count');
                if ($simulation_count >= $simulation_notify_count) {
                    $this->error("模拟通知每天最多只能有{$simulation_notify_count}个！");
                }
            }

            $info['operation_id'] = $this->merchant_id;

            $notify = SimulationNotifyModel::insert($info->toArray());
            if (!$notify) {
                $this->error('记录日志失败！');
            }

            $order_id = $info['order_id'];
            $cash = $info['cash'] / 100;
            $verify_param = $info['verify_param'];
            $other_order_id = 0;
            $payment_company = $info['company'];
            $verify_rule = true;
            $verify_sign = false;
            $all_order_verify = false;

            $order_obj = new ApiPaymentOrderModel();
            $order_obj->notifyAbout($order_id, $info->toArray(), $cash, $cash, $verify_param, $other_order_id, $payment_company, $verify_rule, $verify_sign, $all_order_verify);

            SimulationNotifyModel::where(['order_id' => $data['order_id']])->update(['status' => 2, 'update_time' => time()]);

            $this->success('操作成功，请在订单列表中查看订单状态', url('simulation_notify'));
        }

        $items = [
            ['text', 'order_id', '平台订单号', '输入平台订单号24位'],
            ['password', 'trade_pwd', '交易密码', '6-16位'],
        ];

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('模拟第三方通知') // 设置页面标题
            ->setPageTips("这是一个危险操作,请明白其中的风险！会记录日志。")
            ->addFormItems($items)
            ->fetch();
    }

    /**
     * 模拟订单查看
     * @param null $id 平台订单号
     * @return mixed
     */
    public function simulation_notify_see($id = null)
    {
        if ($this->no_auth) {
            $mconfig = MconfigModel::where(['id' => $this->merchant_id])->find();
            if (!$mconfig || $mconfig['simulation_notify'] != 1) {
                $this->error('权限不足！');
            }
        }
        if ($id === null) {
            $this->error('缺少参数！');
        }

        // 所有的支付类型
        $all_payment_type = pay_config('payment_type');
        // 所有的交易类型
        $all_trade_type = pay_config('trade_type');
        // 所有的订单状态
        $all_order_status = pay_config('order_status');
        // 支付公司
        $all_config_group = pay_config('config_group');
        // 支付公司子商户号
        $all_child_company = PaymentPayCompanyModel::column('title', 'name');

        // 获取数据
        $info = SimulationNotifyModel::where('order_id', $id)->field(true)->find();
        if (!$info) {
            $this->error('不存在！');
        }

        if ($this->no_auth) {
            if ($this->merchant_id != $info['merchant_id']) {
                $this->error('参数错误！');
            }
        }

        if (!$this->key_see_safe) {
            $create_param = json_decode($info['create_param'], true);
            if (isset($create_param['key'])) {
                unset($create_param['key']);
            }
            $info['create_param'] = json_encode($create_param);
            $info['verify_param'] = '';
        }

        $info['cash'] /= 100;
        $info['now_cash'] = $info['now_cash'] ? $info['now_cash'] / 100 : '';
        $info['status'] = $all_order_status[$info['status']];
        $info['trade_type'] = $all_trade_type[$info['trade_type']];
        $info['type'] = $all_payment_type[$info['type']];
        $info['company'] = isset($all_config_group[$info['company']]) ? $all_config_group[$info['company']] : '';
        $info['child_company'] = isset($all_child_company[$info['child_company']]) ? $all_child_company[$info['child_company']] : '';
        $info['create_param'] = format_nice($info['create_param']);
        $info['return_param'] = format_nice($info['return_param']);
        $info['notify_param'] = format_nice($info['notify_param']);

        $items = [
            ['static', 'merchant_id', '商户号', '商户名称：' . get_user_nickname($info['merchant_id']), '', '', ''],
            ['static', 'app_id', '应用id', '', '', '', ''],
            ['static', 'cash', '充值现金（元）', ''],
            ['static', 'now_cash', '实际金额（元）', '', '', '', ''],
            ['static', 'status', '订单状态', '', '', '', ''],
            ['static', 'type', '支付类型', '', '', '', ''],
            ['static', 'trade_type', '交易类型', ''],
            ['datetime', 'create_time', '订单创建时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
            ['datetime', 'update_time', '订单更新时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
            ['static', 'order_id', '平台订单号'],
            ['static', 'merchant_order_id', '商户订单号', '', '', '', ''],
            ['textarea', 'create_param', '创建数据[:无]', '', '', '', ''],
            ['textarea', 'return_param', '返回数据[:无]', '', '', '', ''],
            ['textarea', 'notify_param', '通知数据[:无]', '', '', '', ''],
            ['static', 'other_order_id', '第三方订单号', '', '', '', ''],
            ['static', 'verify_param', '验证参数', ''],
            ['static', 'company', '支付公司', '', '', '', ''],
            ['static', 'child_company', '支付公司子商户号'],
            ['static', 'remark', '备注'],
            ['static', 'operation_id', '操作号', '操作名称：' . get_user_nickname($info['operation_id']), '', '', ''],
        ];
        if ($this->no_auth) {
            unset($items[12]);
            unset($items[13]);
            unset($items[14]);
            unset($items[15]);
            unset($items[16]);
            unset($items[17]);
            unset($items[18]);
            unset($items[19]);
        }
        if ($this->role > $this->have_auth) {
            unset($items[11]);
        }

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('查看') // 设置页面标题
            ->addFormItems($items)
            ->hideBtn('submit')
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    /**
     * 模拟导出数据
     * @return mixed
     */
    public function simulation_notify_export($map = '')
    {
        ini_set('memory_limit', '1024M');
        ob_end_clean();

        if (!is_dir($this->file_path)) {
            $this->error('数据导出目录不存在！', url('index'));
        }
        set_time_limit(3600);

        if (!empty($map)) {
            $map = htmlspecialchars_decode($map);
            $map = urldecode($map);
            $map = str_replace("+", " ", $map);
            // 获取查询条件
            $map = json_decode($map, true);
        }

        // 所有的支付类型
        $all_payment_type = pay_config('payment_type');
        // 所有的交易类型
        $all_trade_type = pay_config('trade_type');
        // 所有的订单状态
        $all_order_status = pay_config('order_status');
        // 所有的支付公司
        $all_config_group = pay_config('config_group');
        unset($all_config_group['pay_config']);
        // 获取所有支付公司的子商户号
        $all_child_company = PaymentPayCompanyModel::column('title', 'name');

        if ($map) {
            foreach ($map as $map_k1 => $map_v1) {

                if ($map_v1[0] == 'merchant_id') {
                    $search_merchant_id_key = $map_k1;
                    $search_merchant_id = $map[$map_k1][2];
                }
            }
        }

        $search_merchant_id_key = isset($search_merchant_id_key) ? $search_merchant_id_key : count($map);

        if ($this->no_auth) {
            $map[$search_merchant_id_key] = ['merchant_id', '=', $this->merchant_id];
        }

        if ($this->is_agent) {
            $sub_merchant = get_sub_merchant($this->merchant_id);
            if ($sub_merchant) {
                $sub_merchant[] = $this->merchant_id;
                $map[$search_merchant_id_key] = ['merchant_id', 'in', $sub_merchant];
                if (isset($search_merchant_id) && in_array($search_merchant_id, $sub_merchant)) {
                    $map[$search_merchant_id_key] = ['merchant_id', '=', $search_merchant_id];
                }
            }
        }

        $count = SimulationNotifyModel::where($map)->count();
        if (empty($count)) {
            $this->error('数据导出为空！', url('index'));
        }
        // 最多导出数量
        $export_order_max_count = pay_config('export_order_max_count');
        if ($count > $export_order_max_count) {
            $this->error("系统设置一次最多导出{$export_order_max_count}条数据！");
        }

        $date = date('Y-m-d');
        // 商户每天最多导出订单次数
        $order_export_day_count = pay_config('order_export_day_count');
        $order_map[] = ['merchant_id', '=', $this->merchant_id];
        $order_map[] = ['create_time', 'between time', ["$date 00:00:00", "$date 23:59:59"]];
        $download_count = DownloadModel::where($order_map)->count();
        if ($download_count >= $order_export_day_count) {
            $this->error("系统设置商户每天最多导出订单次数是{$order_export_day_count}次！");
        }

        $download['id'] = date('YmdHis') . rand(100000, 999999);
        $download['merchant_id'] = $this->merchant_id;
        $download['title'] = "模拟支付订单导出条数（{$count}）";
        $download['file_name'] = $download['id'] . '.csv';
        $download['url'] = Request::module() . '/' . Request::controller() . '/' . Request::action();
        $download['status'] = 2;
        $download['programmer_remark'] = json_encode($map);
        $download_insert = DownloadModel::create($download);
        if (!$download_insert) {
            $this->error("导出失败");
        }

        $field = [
            'order_id',
            'operation_id',
            'merchant_id',
            'app_id',
            'cash',
            'status',
            'type',
            'trade_type',
            'create_time',
            'update_time',
            'merchant_order_id',
            'company',
            'child_company',
            'other_order_id',
        ];
        if ($this->no_auth) {
            unset($field[11]);
            unset($field[12]);
            unset($field[13]);
        }

        $cellName = [
            '平台订单号',
            '操作号',
            '商户号',
            '应用ID',
            '金额',
            '订单状态',
            '支付类型',
            '交易类型',
            '创建时间',
            '更新时间',
            '商户订单号',
            '支付公司',
            '支付公司子商户号',
            '第三方订单号',
        ];
        if ($this->no_auth) {
            unset($cellName[11]);
            unset($cellName[12]);
            unset($cellName[13]);
        }
        $fp = fopen($download['file_name'], 'w');

        foreach ($cellName as $key => $value) {
            $cellName[$key] = mb_convert_encoding($cellName[$key], 'gb2312', 'utf-8');
        }

        fputcsv($fp, $cellName);

        Db::name('payment_order_simulation_notify')
            ->where($map)
            ->field($field)
            ->chunk(200, function ($all) use ($fp, $all_order_status, $all_payment_type, $all_trade_type, $all_config_group, $all_child_company) {
                foreach ($all as $single) {

                    $single['cash'] /= 100;
                    $single['status'] = $all_order_status[$single['status']];

                    $single['type'] = $all_payment_type[$single['type']];

                    $single['trade_type'] = $all_trade_type[$single['trade_type']];

                    $single['create_time'] = date('Y-m-d H:i:s', $single['create_time']);
                    $single['update_time'] = $single['update_time'] ? date('Y-m-d H:i:s', $single['update_time']) : 0;

                    if (isset($single['company'])) {
                        $single['company'] = isset($all_config_group[$single['company']]) ? $all_config_group[$single['company']] : $single['company'];
                    }
                    if (isset($single['child_company'])) {
                        $single['child_company'] = isset($all_child_company[$single['child_company']]) ? $all_child_company[$single['child_company']] : $single['child_company'];
                    }

                    foreach ($single as $key => $value) {
                        if (!in_array($key, ['cash', 'merchant_id'])) {
                            $single[$key] = "\t" . mb_convert_encoding($value, 'gb2312', 'utf-8');
                        }
                    }

                    fputcsv($fp, $single);
                    unset($single);
                }
            }, 'order_id', 'desc');
        fclose($fp);

        DownloadModel::update(['id' => $download['id'], 'status' => 1, 'update_time' => time()]);
        rename(Env::get('root_path') . 'public' . DIRECTORY_SEPARATOR . $download['file_name'], $this->file_path . $download['file_name']); // 移动到新目录

        $this->success('导出成功', url('download/index'));
    }
}
